{
    open Parser
}

(*词法分析器lexer，将输入高级语言代码字符串分解为tokens，为后续语法分析Parser提供结构化的输入*)

rule read = parse 
    (* 空白字符处理 *)
    | [' ' '\t' '\n'] { read lexbuf }
    
    (* 单行注释 *)
    | "//" [^ '\n']* '\n' { read lexbuf }
    
    (* 多行注释 *)
    | "/*" { comment lexbuf }
    
    (*换行符*)
    | '\r'? '\n'        { Lexing.new_line lexbuf; read lexbuf} 

    (* 关键字 *)
    | "int"     { INT_TYPE }
    | "void"    { VOID }
    | "if"      { IF }
    | "else"    { ELSE }
    | "while"   { WHILE }
    | "break"   { BREAK }
    | "continue" { CONTINUE }
    | "return"  { RETURN }
    
    (* 运算符和标点 *)
    | '+'   { PLUS }
    | '-'   { MINUS }
    | '*'   { TIMES }
    | '/'   { DIV }
    | '%'   { MOD }
    | '!'   { NOT }
    | '='   { ASSIGN }
    | "=="  { EQ }
    | "!="  { NEQ }
    | '<'   { LT }
    | ">"   { GT }
    | "<="  { LEQ }
    | ">="  { GEQ }
    | "&&"  { AND }
    | "||"  { OR }
    
    (* 分隔符 *)
    | '('   { LPAREN }
    | ')'   { RPAREN }
    | '{'   { LBRACE }
    | '}'   { RBRACE }
    | ';'   { SEMICOLON }
    | ','   { COMMA }
    
    (* 标识符和整数 *)
    | ['0'-'9']+ as num { NUMBER (int_of_string num) }
    | ['a'-'z' 'A'-'Z' '_']['a'-'z' 'A'-'Z' '0'-'9' '_']* as id { ID id }
    
    (* 文件结束 *)
    | eof   { EOF }
    
    (* 无效字符处理 *)
    | _     { failwith ("Invalid character: " ^ Lexing.lexeme lexbuf) }

and comment = parse
    | "*/"  { read lexbuf }
    | _     { comment lexbuf }
    | eof   { failwith "Unterminated comment" }